package com.zhihu_lvliangi_android.option.parent;

import java.lang.reflect.Method;

import org.apache.http.HttpStatus;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.task.TaskCallBack;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.zhihu_lvliangi_android.R;
import com.zhihu_lvliangi_android.option.HomePageActivity;
import com.zhihu_lvliangi_android.service.ClientTask;
import com.zhihu_lvliangi_android.service.MobileApplication;

/**
 * Activity父类
 * 
 * @author azuryleaves
 * @since 2014-3-9 下午5:06:12
 * @version 1.0
 * 
 */
public abstract class ParentActivity extends BasicActivity implements TaskCallBack, ClientTask.ResponseErrorListener {

	/**
	 * 全局的Context {@link #mContext = this.getApplicationContext();}
	 */
	protected Context mContext;
	protected SharedPreferences preferences;
	protected ActionBarListener actionBarListener;
//	protected ActionBar actionBar;
	protected TextView actionBarTitle;
	protected ImageButton leftImageButton, rightImageButton;
	protected Gson gson = new Gson();
	private long exitTime = 0;
	private boolean loginIsShown = false;

	protected ParentFragment fragment;
	private Class<?>[] fragments = {  };
	
	public interface ActionBarListener {
		
		public void onClick(View view);
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int layoutId = getLayoutId();
		if (layoutId == 0) {
			Log.e(ParentActivity.class.getSimpleName(), "请添加ContentView布局文件");
		} else {
			setContentView(layoutId);
		}

		mContext = this.getApplicationContext();
		preferences = getSharedPreferences(MobileApplication.TAG, Context.MODE_PRIVATE);

		// 初始化组件
		setupViews();
		// 初始化数据
		initialized();
		MobileApplication.taskCallBacks.put(this.getClass().getName(), this);
		threadTask();
	}
	
	public void turnToFragmentAdd(int layoutId, Class<? extends ParentFragment> fragmentClass, Bundle args) {
		fragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(fragmentClass.getName());
		boolean isFragmentExist = true;
		if (fragment == null) {
			try {
				isFragmentExist = false;
				fragment = fragmentClass.newInstance();
				fragment.setArguments(args);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (args != null && !args.isEmpty()) {
			fragment.getArguments().putAll(args);
		}
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		if (isFragmentExist) {
			for (int i = 0; i < fragments.length; i++) {
				ParentFragment tempFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(fragments[i].getClass().getName());
				if (tempFragment != null) {
					if (tempFragment.isHidden()) {
						if (tempFragment.getClass().getName().equals(fragmentClass.getName())) {
							ft.show(tempFragment);
//							System.out.println("---tempFragment---show---" + tempFragment.getClass().getName());
						} else {
							ft.hide(tempFragment);
//							System.out.println("---tempFragment---hide---" + tempFragment.getClass().getName());
						}
					}
				}
			}
		} else {
			ft.add(layoutId, fragment, fragmentClass.getName());
			ft.addToBackStack(fragmentClass.getName());
		}
		ft.commitAllowingStateLoss();
	}

	public void turnToFragmentReplace(int layoutId, Class<? extends ParentFragment> fragmentClass, Bundle args) {
		fragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(fragmentClass.getName());
		if (fragment == null) {
			try {
				fragment = fragmentClass.newInstance();
				fragment.setArguments(args);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (args != null && !args.isEmpty()) {
			fragment.getArguments().putAll(args);
		}
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.replace(layoutId, fragment);
		ft.commitAllowingStateLoss();
	}

	/**
	 * 利用反射让隐藏在Overflow中的MenuItem显示Icon图标
	 * 
	 * @param featureId
	 * @param menu
	 *            onMenuOpened方法中调用
	 */
	public static void setOverflowIconVisible(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		setOverflowIconVisible(featureId, menu);
		return super.onMenuOpened(featureId, menu);
	}

	/**
	 * 获取全局的Context
	 * 
	 * @return {@link #mContext = this.getApplicationContext();}
	 */
	public Context getContext() {
		return mContext;
	}

	/**
	 * 布局文件ID
	 * 
	 * @return
	 */
	protected abstract int getLayoutId();

	/**
	 * 初始化组件
	 */
	protected abstract void setupViews();

	/**
	 * 初始化数据
	 */
	protected abstract void initialized();

	/**
	 * 需要线程池操作的任务
	 * 
	 */
	protected abstract void threadTask();

	/**
	 * 长时间显示Toast提示(来自String)
	 * 
	 * @param message
	 */
	protected void showToast(String message) {
		Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * 长时间显示Toast提示(来自res)
	 * 
	 * @param resId
	 */
	protected void showToast(int resId) {
		Toast.makeText(mContext, getString(resId), Toast.LENGTH_LONG).show();
	}

	/**
	 * 短暂显示Toast提示(来自res)
	 * 
	 * @param resId
	 */
	protected void showShortToast(int resId) {
		Toast.makeText(mContext, getString(resId), Toast.LENGTH_SHORT).show();
	}

	/**
	 * 短暂显示Toast提示(来自String)
	 * 
	 * @param text
	 *            .
	 */
	protected void showShortToast(String text) {
		Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 通过Class跳转界面
	 **/
	public void startActivity(Class<?> cls) {
		startActivity(cls, null);
	}

	/**
	 * 含有Bundle通过Class跳转界面
	 **/
	public void startActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent();
		intent.setClass(this, cls);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 通过Action跳转界面
	 **/
	public void startActivity(String action) {
		startActivity(action, null);
	}

	/**
	 * 含有Bundle通过Action跳转界面
	 **/
	public void startActivity(String action, Bundle bundle) {
		Intent intent = new Intent();
		intent.setAction(action);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 含有Bundle通过Class打开编辑界面
	 **/
	public void startActivityForResult(Class<?> cls, int requestCode) {
		startActivityForResult(cls, null, requestCode);
	}

	/**
	 * 含有Bundle通过Class打开编辑界面
	 **/
	public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
		Intent intent = new Intent();
		intent.setClass(this, cls);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 带有右进右出动画的退出
	 */
	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	/**
	 * 默认退出
	 */
	public void defaultFinish() {
		super.finish();
	}

	public boolean onBackKeyDown(int backStackCount, KeyEvent event) {
		return getSupportFragmentManager().popBackStackImmediate();
	}
	
	@Override
	public void onBackPressed() {
		int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
		System.out.println("------SlidingMenu控制组------backStackCount------" + backStackCount);
		if (backStackCount > 1) {
			 onBackKeyDown(backStackCount, null);
			 return;
		} 
		if (HomePageActivity.class.getName().equals(this.getClass().getName())) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				showShortToast(R.string.exit_app);
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
		} else {
			finish();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		/*if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
			int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
			System.out.println("------SlidingMenu控制组------backStackCount------" + backStackCount);
			if (backStackCount > 1) {
				return onBackKeyDown(backStackCount, event);
			} else {
				if (event.getRepeatCount() == 0) {
					if (HomePageActivity.class.getName().equals(this.getClass().getName())) {
						if ((System.currentTimeMillis() - exitTime) > 2000) {
							showShortToast(R.string.exit_app);
							exitTime = System.currentTimeMillis();
						} else {
							finish();
							System.exit(0);
						}
					} else {
						finish();
					}
					return true;
				} else {
					return super.dispatchKeyEvent(event);
				}
			}
		} else {*/
			return super.dispatchKeyEvent(event);
//		}
	}

	@Override
	public void refresh(Enum<?> taskID, Object... param) {

	}

	@Override
	public void onErrorResponse(VolleyError error) {
		switch (error.networkResponse.statusCode) {
		case HttpStatus.SC_BAD_REQUEST: // -- 请求有误：Header、参数
			showToast("请求有误：Header、参数, 错误码：" + error.networkResponse.statusCode);
			break;
		case HttpStatus.SC_FORBIDDEN: // -- 无权访问
			if (!loginIsShown) { // -- 避免重复跳转登录
				//-- 一般此处跳转至登录页
				
				loginIsShown = true;
			}
			break;
		case HttpStatus.SC_NOT_FOUND: // -- 页面不存在
			showToast("页面不存在, 错误码：" + error.networkResponse.statusCode);
			break;
		case HttpStatus.SC_METHOD_NOT_ALLOWED: // -- 请求方法不允许
			showToast("请求方法不允许, 错误码：" + error.networkResponse.statusCode);
			break;
		case HttpStatus.SC_REQUEST_TIMEOUT: // --请求超时
			showToast("请求超时, 错误码：" + error.networkResponse.statusCode);
			break;
		case HttpStatus.SC_INTERNAL_SERVER_ERROR: // -- 服务器异常
			showToast("服务器异常, 错误码：" + error.networkResponse.statusCode);
			break;
		default:
			showToast("错误码：" + error.networkResponse.statusCode);
			break;
		}
	}

}
